/*
 * Operador.java
 *
 * Created on 21/10/2011, 01:04:25
 */
package org.acervus.gui;

import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import org.acervus.operador.OperadorBean;
import org.acervus.operador.OperadorController;

/**
 * @author Eziel Soares, Giordano Giuliano, Lenilson Regis
 */

public class Operador extends javax.swing.JFrame {
    DefaultTableModel tmOperador = new DefaultTableModel(null, new String[]{"Id", "Matrícula", "Login", "Nome"});
    ListSelectionModel lsmOperador;
    List<OperadorBean> operador;
    String tipoCadastro;

    /** Creates new form Operador */
    public Operador() {
        initComponents();
        this.setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel6 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tfLogin = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        tfNome = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        tfMatricula = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        tfPesquisarOperador = new javax.swing.JTextField();
        btPesquisar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbOperador = new javax.swing.JTable();
        jLabel7 = new javax.swing.JLabel();
        tfEmail = new javax.swing.JTextField();
        btExcluir = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();
        btFechar = new javax.swing.JButton();
        btAdicionar = new javax.swing.JButton();
        pfSenha = new javax.swing.JPasswordField();
        btCancelar = new javax.swing.JButton();
        btSalvar = new javax.swing.JButton();

        jLabel6.setText("jLabel6");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Operador");
        setResizable(false);

        jLabel1.setText("Login:");

        jLabel2.setText("Senha:");

        tfLogin.setEnabled(false);

        jLabel3.setText("Nome:");

        tfNome.setEnabled(false);

        jLabel4.setText("Matrícula:");

        tfMatricula.setEnabled(false);

        jLabel5.setText("Operador:");

        btPesquisar.setText("Pesquisar");
        btPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarActionPerformed(evt);
            }
        });

        tbOperador.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tbOperador.setModel(tmOperador);
        tbOperador.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lsmOperador = tbOperador.getSelectionModel();
        lsmOperador.addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent e) {
                if (! e.getValueIsAdjusting()){
                    tbOperadorLinhaSelecionada(tbOperador);
                    btAlterar.setEnabled(true);
                    btExcluir.setEnabled(true);
                }

            }
        });
        listarOperador();
        jScrollPane1.setViewportView(tbOperador);

        jLabel7.setText("Email:");

        tfEmail.setEnabled(false);

        btExcluir.setText("Excluir");
        btExcluir.setEnabled(false);
        btExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirActionPerformed(evt);
            }
        });

        btAlterar.setText("Alterar");
        btAlterar.setEnabled(false);
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });

        btFechar.setText("Fechar");
        btFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btFecharActionPerformed(evt);
            }
        });

        btAdicionar.setText("Adicionar");
        btAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAdicionarActionPerformed(evt);
            }
        });

        pfSenha.setText("jPasswordField1");
        pfSenha.setEnabled(false);

        btCancelar.setText("Cancelar");
        btCancelar.setEnabled(false);
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });

        btSalvar.setText("Salvar");
        btSalvar.setEnabled(false);
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(90, 90, 90)
                        .addComponent(jLabel7))
                    .addComponent(tfNome, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, 0, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfPesquisarOperador, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(tfMatricula, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(tfLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(pfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btAdicionar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btExcluir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btAlterar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btSalvar))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btCancelar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btFechar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(btPesquisar)
                    .addComponent(tfPesquisarOperador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btSalvar)
                            .addComponent(btAlterar)
                            .addComponent(btExcluir)
                            .addComponent(btAdicionar))
                        .addGap(12, 12, 12)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfMatricula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btFechar)
                    .addComponent(btCancelar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAdicionarActionPerformed
        // TODO add your handling code here:
        tipoCadastro = "novo";
        novoOperador();
    }//GEN-LAST:event_btAdicionarActionPerformed

    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed
        // TODO add your handling code here:
        desabilitarCampos();
    }//GEN-LAST:event_btCancelarActionPerformed

    private void btFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFecharActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btFecharActionPerformed

    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
        // TODO add your handling code here:
        if (tipoCadastro.equals("novo")) {
            cadastrarOperador();
        } else if (tipoCadastro.equals("alteração")) {
            alterarOperador();
        }
    }//GEN-LAST:event_btSalvarActionPerformed

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
        // TODO add your handling code here:
        tipoCadastro = "alteração";
        habilitarCampos();
    }//GEN-LAST:event_btAlterarActionPerformed

    private void btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarActionPerformed
        // TODO add your handling code here:
        listarOperador();
    }//GEN-LAST:event_btPesquisarActionPerformed

    private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
        // TODO add your handling code here:
        excluirOperador();
    }//GEN-LAST:event_btExcluirActionPerformed
    
    private void habilitarCampos() {
        tfLogin.setEnabled(true);
        pfSenha.setEnabled(true);
        tfEmail.setEnabled(true);
        tfNome.setEnabled(true);
        tfMatricula.setEnabled(true);
        btCancelar.setEnabled(true);
        btSalvar.setEnabled(true);
    }
    
    private void desabilitarCampos() {
        tfLogin.setEnabled(false);
        pfSenha.setEnabled(false);
        tfEmail.setEnabled(false);
        tfNome.setEnabled(false);
        tfMatricula.setEnabled(false);
        btCancelar.setEnabled(false);
        btSalvar.setEnabled(false);
    }
    
    private void limparCampos() {
        tfLogin.setText("");
        pfSenha.setText("");
        tfEmail.setText("");
        tfNome.setText("");
        tfMatricula.setText("");
    }
    
    private void novoOperador() {
        limparCampos();
        habilitarCampos();
    }
    
    private void cadastrarOperador() {
        if (verificarCampos()) {
            OperadorBean operador = new OperadorBean();
            operador.setLogin(tfLogin.getText().trim());
            String senha = new String(pfSenha.getPassword());
            operador.setSenha(senha);
            operador.setNome(tfNome.getText().trim());
            operador.setMatricula(tfMatricula.getText().trim());
            operador.setEmail(tfEmail.getText().trim());

            OperadorController op = new OperadorController();
            op.cadastrarOperador(operador);
            desabilitarCampos();
            JOptionPane.showMessageDialog(this, "Operador cadastrado com sucesso!");
            listarOperador();
        }
    }
    
    private boolean verificarCampos(){
        // Verifica se há dados no campo: login
        if (!tfLogin.getText().trim().equals("")) {
            return true;
        } else {
            JOptionPane.showMessageDialog(this, "O campo LOGIN está vazio!");
        }
        
        // Verifica se há dados no campo: senha
        if (!pfSenha.getText().trim().equals("")) {
            return true;
        } else {
            JOptionPane.showMessageDialog(this, "O campo SENHA está vazio!");
        }
        
        // Verifica se há dados no campo: nome
        if (!tfNome.getText().trim().equals("")) {
            return true;
        } else {
            JOptionPane.showMessageDialog(this, "O campo NOME está vazio!");
        }

        // Verifica se há dados no campo: matricula
        if (!tfMatricula.getText().trim().equals("")) {
            return true;
        } else {
            JOptionPane.showMessageDialog(this, "O campo MATRÍCULA está vazio!");
        }
        
        // Verifica se há dados no campo: email
        if (!tfEmail.getText().trim().equals("")) {
            return true;
        } else {
            JOptionPane.showMessageDialog(this, "O campo EMAIL está vazio!");
        }
        return false;
    }
    
    private void listarOperador() {
        OperadorController op = new OperadorController();
        operador = op.listarOperador("%" + tfPesquisarOperador.getText().trim() + "%");
        mostrarOperador(operador);
    }
    
    private void mostrarOperador(List<OperadorBean> operador) {

        while (tmOperador.getRowCount() > 0) {
            tmOperador.removeRow(0);
        }

        if (operador.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Nenhum operador encontrado!");
        } else {
            String[] campos = new String[]{null, null, null, null};
            for (int i = 0; i < operador.size(); i++) {
                tmOperador.addRow(campos);
                tmOperador.setValueAt(operador.get(i).getId(), i, 0);
                tmOperador.setValueAt(operador.get(i).getMatricula(), i, 1);
                tmOperador.setValueAt(operador.get(i).getLogin(), i, 2);
                tmOperador.setValueAt(operador.get(i).getNome(), i, 3);
            }
        }
    }
    
    private void tbOperadorLinhaSelecionada(JTable tb) {
        if (tb.getSelectedRow() != -1) {
            tfLogin.setText(operador.get(tb.getSelectedRow()).getLogin());
            pfSenha.setText(operador.get(tb.getSelectedRow()).getSenha());
            tfNome.setText(operador.get(tb.getSelectedRow()).getNome());
            tfMatricula.setText(operador.get(tb.getSelectedRow()).getMatricula());     
            tfEmail.setText(operador.get(tb.getSelectedRow()).getEmail());     
        } else {
            tfLogin.setText("");
            pfSenha.setText("");
            tfNome.setText("");
            tfMatricula.setText("");
            tfEmail.setText("");
        }
    }
    
    private void alterarOperador() {
        if (verificarCampos()) {
            OperadorBean oper = new OperadorBean();
            oper.setId(operador.get(tbOperador.getSelectedRow()).getId());
            oper.setLogin(tfLogin.getText().trim());
            oper.setSenha(pfSenha.getPassword().toString());
            oper.setMatricula(tfMatricula.getText().trim());
            oper.setEmail(tfEmail.getText().trim());
            oper.setNome(tfNome.getText().trim());
            
            OperadorController op = new OperadorController();
            op.alterarOperador(oper);
            desabilitarCampos();
            btAlterar.setEnabled(false);
            JOptionPane.showMessageDialog(this, "Dados Alterados!");
            listarOperador();
        } else {
            JOptionPane.showMessageDialog(this, "Informe o nome do operador!");
            tfNome.requestFocus();
        }
    }
    
    private void excluirOperador() {
        int opcao;
        
        OperadorBean oper = new OperadorBean();
        oper.setId(operador.get(tbOperador.getSelectedRow()).getId());
        oper.setNome(tfNome.getText().trim());
        
        opcao = JOptionPane.showConfirmDialog(null, "Tem certeza que deseja excluir o operador "+ oper.getNome() +"?", "Excluir Operador",
                                      JOptionPane.YES_NO_OPTION);
        
        if (opcao == JOptionPane.YES_OPTION) {
            OperadorController op = new OperadorController();
            op.removerOperador(oper);
            listarOperador();
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Operador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Operador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Operador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Operador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Operador().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAdicionar;
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btExcluir;
    private javax.swing.JButton btFechar;
    private javax.swing.JButton btPesquisar;
    private javax.swing.JButton btSalvar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPasswordField pfSenha;
    private javax.swing.JTable tbOperador;
    private javax.swing.JTextField tfEmail;
    private javax.swing.JTextField tfLogin;
    private javax.swing.JTextField tfMatricula;
    private javax.swing.JTextField tfNome;
    private javax.swing.JTextField tfPesquisarOperador;
    // End of variables declaration//GEN-END:variables
}
